//package com.cl.cloud.tenant.config;
//
//import com.sicpay.support.props.JinxinProperties;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.http.client.HttpClient;
//import org.apache.http.config.Registry;
//import org.apache.http.config.RegistryBuilder;
//import org.apache.http.conn.socket.ConnectionSocketFactory;
//import org.apache.http.conn.socket.PlainConnectionSocketFactory;
//import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
//import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
//import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
//import org.apache.http.impl.client.HttpClientBuilder;
//import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
//import org.apache.http.ssl.SSLContextBuilder;
//import org.apache.http.ssl.SSLContexts;
//import org.apache.http.ssl.TrustStrategy;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.http.client.ClientHttpRequestFactory;
//import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
//import org.springframework.http.converter.HttpMessageConverter;
//import org.springframework.http.converter.StringHttpMessageConverter;
//import org.springframework.web.client.DefaultResponseErrorHandler;
//import org.springframework.web.client.RestTemplate;
//
//import javax.net.ssl.SSLContext;
//import java.io.FileInputStream;
//import java.nio.charset.Charset;
//import java.nio.charset.StandardCharsets;
//import java.security.KeyStore;
//import java.security.cert.CertificateException;
//import java.security.cert.X509Certificate;
//import java.util.List;
//
///**
// * @description:
// * @author: liuzijian
// * @time: 2022-05-06 09:39
// */
//@Slf4j
//@Configuration
//public class HttpsConfiguration {
//
//    @Autowired
//    private JinxinProperties jinxinProperties;
//
//    /**
//     * 初始化RestTemplate,并加入spring的Bean工厂，由spring统一管理
//     */
//    @Bean(name = "httpsClientTemplate")
//    public RestTemplate restTemplate(@Qualifier("clientHttpsRequestFactory") ClientHttpRequestFactory factory) {
//        RestTemplate restTemplate = new RestTemplate(factory);
//        //采用RestTemplate内部的MessageConverter
//        //重新设置StringHttpMessageConverter字符集，解决中文乱码问题
//        modifyDefaultCharset(restTemplate);
//        //设置错误处理器
//        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
//        return restTemplate;
//    }
//
//    /**
//     * 修改默认的字符集类型为utf-8
//     *
//     * @param restTemplate
//     */
//    private void modifyDefaultCharset(RestTemplate restTemplate) {
//        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
//        HttpMessageConverter<?> converterTarget = null;
//        for (HttpMessageConverter<?> item : converterList) {
//            if (StringHttpMessageConverter.class == item.getClass()) {
//                converterTarget = item;
//                break;
//            }
//        }
//        if (null != converterTarget) {
//            converterList.remove(converterTarget);
//        }
//        Charset defaultCharset = StandardCharsets.UTF_8;
//        converterList.add(1, new StringHttpMessageConverter(defaultCharset));
//    }
//
//    /**
//     * 创建HTTP客户端工厂
//     *
//     * @return
//     */
//    @Bean("clientHttpsRequestFactory")
//    public ClientHttpRequestFactory clientHttpsRequestFactory(@Qualifier("httpsClient") HttpClient httpClient) {
//        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
//        // 连接超时
//        clientHttpRequestFactory.setConnectTimeout(jinxinProperties.getConnetTimeOut());
//        // 数据读取超时时间，即SocketTimeout
//        clientHttpRequestFactory.setReadTimeout(jinxinProperties.getReadTimeOut());
//        // 从连接池获取请求连接的超时时间，不宜过长，必须设置，比如连接不够用时，时间过长将是灾难性的
//        clientHttpRequestFactory.setConnectionRequestTimeout(4000);
//        return clientHttpRequestFactory;
//    }
//
//    @Bean("httpsClient")
//    public HttpClient httpClient() throws Exception{
//        try {
//            //设置信任ssl访问
//            SSLContextBuilder builder = SSLContexts.custom();
//            builder.loadTrustMaterial(null, new TrustStrategy() {
//                @Override
//                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
//                    return true;
//                }
//            });
//            this.buildJinxinKeyStore(builder);
//
//            SSLContext sslcontext = builder.build();
//            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, (hostname, session) -> true);
//            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
//                    // 注册http和https请求
//                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
//                    .register("https", sslConnectionSocketFactory).build();
//            PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
//            // 最大连接数
//            poolingHttpClientConnectionManager.setMaxTotal(500);
//            // 同路由并发数 设置过小无法支持大并发 路由是对maxTotal的细分
//            poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100);
//
//            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//            //禁用cookie
//            httpClientBuilder.disableCookieManagement();
//            //是否共享连接池
//            httpClientBuilder.setConnectionManagerShared(true);
//            //配置连接池
//            httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
//            //设置长链接策略
//            //httpClientBuilder.setKeepAliveStrategy();
//            // 重试次数
//            httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true));
//            return httpClientBuilder.build();
//        } catch (Exception e) {
//            log.error("http连接池初始化出错", e);
//            throw e;
//        }
//    }
//
//    /**
//     * 加载金信反欺诈客户端证书
//     * @param builder
//     */
//    private void buildJinxinKeyStore(SSLContextBuilder builder) {
//        try (FileInputStream is = new FileInputStream(jinxinProperties.getKeystorePath())) {
//            char[] passwordChars = jinxinProperties.getKeystorePassword().toCharArray();
//            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
//            ks.load(is, passwordChars);
//            builder.loadKeyMaterial(ks, passwordChars);
//        } catch (Exception e) {
//            log.info("【金信反欺诈】获取KeyStore失败");
//            //throw new RuntimeException(e);
//        }
//    }
//
//    private void buildJinxinTrustStore(SSLContextBuilder builder) {
//        try (FileInputStream is = new FileInputStream(jinxinProperties.getTruststorePath())) {
//            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
//            ks.load(is, jinxinProperties.getTruststorePassword().toCharArray());
//            builder.loadTrustMaterial(ks, new TrustSelfSignedStrategy());
//        } catch (Exception e) {
//            log.info("【金信反欺诈】获取KeyStore失败");
//            //throw new RuntimeException(e);
//        }
//    }
//
//}
